﻿using System;
using System.Net.Http;
using System.Text;
using System.Web.Http.Filters;
using YouWei.Api.Models;
using Newtonsoft.Json;
using YouWei.Api.Common;
using YouWei.Utility.Logging;
using YouWei.Utility;

namespace YouWei.Api.Filters
{
    /// <summary>
    /// 异常处理
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class APIExceptionFilterAttribute : ExceptionFilterAttribute
    {
        /// <summary>
        /// 重写异常处理
        /// </summary>
        /// <param name="actionExecutedContext"></param>
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {

            if (actionExecutedContext.Exception != null)
            {
                //api2的错误,屏蔽
                if (actionExecutedContext.Exception.Message.StartsWith("已取消该操作"))
                {
                    return;
                }
                var actionContext = actionExecutedContext.ActionContext;
                //记录安全日志
                try
                {
                    Log4netLog.Error(new ErrorLog()
                    {
                        ClientIP = IPHelper.IPAddress,
                        CreatedDate = DateTime.Now,
                        ErrorMessage = actionExecutedContext.Exception.Message,
                        ErrorSource = actionExecutedContext.Exception.Source,
                        ErrorTrace = actionExecutedContext.Exception.StackTrace,
                        RequestUrl = actionContext.Request.RequestUri.PathAndQuery,
                        Platform = 3,
                        PostData = PostData(actionContext.Request)

                    });
                }
                catch (Exception ex)
                {
                    Log4netLog.Debug(ex.Message);
                }

                var result = new ResultData();
                result.status = -1;
                result.message = "服务器内部异常";
                result.data = "";
                actionContext.Response = new HttpResponseMessage { Content = new StringContent(JsonConvert.SerializeObject(result), Encoding.GetEncoding("UTF-8"), "application/json") }; ;
                actionContext.Response.Headers.Add("Access-Control-Allow-Headers", "*");
                actionContext.Response.Headers.Add("Access-Control-Allow-Methods", "*");
                //响应头添加Access-Control-Allow-Origin *是全部允许，如果允许某个域名，则直接写域名 
                actionContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");

                return;
            }

        }

        /// <summary>
        /// 获取post数据
        /// </summary>
        /// <param name="Request"></param>
        /// <returns></returns>
        public string PostData(HttpRequestMessage Request)
        {
            if (Request.Content.IsMimeMultipartContent())
            {
                return "";
            }
            try
            {
                Request.Content.ReadAsStreamAsync().Result.Seek(0, System.IO.SeekOrigin.Begin);
                return Request.Content.ReadAsStringAsync().Result;
            }catch(Exception ex)
            {
                return ex.Message;
            }

        }
    }
}